package example.model;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

public class App {
    private Map<String,User> users = new TreeMap<String,User>();
    private Iterable<User> list;

    public App() {
        createUser("jsmith", "pwd");
    }

    public synchronized Iterable<User> userList() {
        if (list == null) {
            list = new ArrayList(users.values());
        }

        return list;
    }

    public synchronized User createUser(String name, String password) {
        if (users.get(name) != null) {
            throw new IllegalArgumentException(
                "User already exists.");
        }

        User user = new User();
        user.name = name;
        user.password = password;

        users.put(user.name, user);
        list = null;
        return user;
    }

    public synchronized User getUser(String name) {
        return users.get(name);
    }

    public synchronized User login(String name, String password) {
        User user = users.get(name);

        if (user == null ||
            !user.password.equals(password))
        {
            throw new IllegalArgumentException(
                "Invalid username or password.");
        }

        return user;
    }
}
